<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>hello vue</title>
<link rel="stylesheet" href="./lib/lib/css/bootstrap.min.css">
<script src="vue.js"></script>
<style type="text/css">

</style>
</head>
<body>



<div id="app" class="container">

	<cmt-box @func='loadComments'></cmt-box>

	 <ul class="list-group">
		<li class="list-group-item" v-for="item in list" ><!-- :key='item.id' -->
			<span class="badge">评论人：{{item.user}}</span>
			<p>{{item.content}}</p>
		</li>
	 </ul>  

</div>




<template id="tmp1">
<div><!-- 因为template的子元素是唯一的，所以用一个div大盒子包含所有 -->
	<div>
		<div class="form-group">
			<label for="">评论人：</label>
			<input type="text" class="form-control" v-model='user'>
		</div>
	</div>

	<div>
		<div class="form-group">
			<label for="">评论内容：</label>
			<textarea class="form-control" v-model="content"></textarea>
		</div>
	</div>
	
	<div>
		<input type="button" class="btn btn-primary" value="发表评论" @click="postComment">
	</div><br>

</div>
</template>





<br>

<script type="text/javascript">

var commentBox = {
	data(){
		return {
			user:'',
			content:''
		}
	},
	template:'#tmp1',
	methods:{
		postComment(){

			var  comment = {id: Date.now(), user:this.user, content:this.content}
			// localStorage.getItem("cmts")  ||  '[]'

			var list = JSON.parse(localStorage.getItem('cmts') || '[]' )//转换为字符串
			list.unshift(comment)
			localStorage.setItem('cmts',JSON.stringify(list))
			this.user = this.content = ''
			this.$emit('func')
		}
	},


}



var app = new Vue({
  el: '#app',

  data: {
  	list:[
  		{id:Date.now(), user:'虞姬', content:'明媚如风，轻盈似箭'},
  		{id:Date.now(), user:'李白', content:'天生我材必有用'},
  		{id:Date.now(), user:'妲己', content:'为什么会痛苦，一直微笑就好了'}
  	],

  	 
  },

  beforeCreate(){//生命周期的页面加载之前，这时data和methods都还没被初始化

  },
  created(){
  		this.loadComments()
  },

  methods:{
  	loadComments(){
  		var list = JSON.parse(localStorage.getItem('cmts') || '[]' )
  		this.list = list

  	}

  },

  components:{
  	'cmt-box': commentBox
  }

})





</script>

	
</body>
</html>